package caronas.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Restrictions;

import br.com.caelum.vraptor.ioc.Component;
import caronas.modelo.Carona;
import caronas.modelo.Usuario;

@Component
public class CaronaDao {
	
	private Session session;
	private SessionFactory factory;
	public CaronaDao(Session session, SessionFactory factory) {
		AnnotationConfiguration configuration = new AnnotationConfiguration();
		configuration.configure();
		this.factory = factory;
		this.session = session;
	}
	
	public void adicionar(Carona carona) {
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(carona);
		tx.commit();
	}
	
	public void atualizar(Carona carona) {
		Transaction tx = session.beginTransaction();
		session.update(carona);
		tx.commit();
	}
	
	public Carona carregar(Long id) {
		return (Carona) session.get(Carona.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public List<Carona> listar(Usuario usuario, String scope) {
		
		Criteria criteria = session.createCriteria(Carona.class);
		if(scope != null){	
			if(scope.equals("mine")){
				criteria.add(Restrictions.eq("usuario", usuario));
			}
			else if(scope.equals("taken")){
				criteria.createAlias("passageiros", "pg");
				criteria.add( Restrictions.eq("pg.id", usuario != null ? usuario.getId() : null));
			}
			
		}
		return criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Carona> listar() {
		
		Criteria criteria = session.createCriteria(Carona.class);
		
		return criteria.list();
	}
	
	public void remover(Long id) {
		Transaction tx = session.beginTransaction();
		Carona carona = (Carona)session.load(Carona.class, id);
		session.delete(carona);
		tx.commit();
		
		  
	}
	
	public void decrementarVagas(Carona carona){
		carona.setVagas(carona.getVagas() - 1);
		Transaction tx = session.beginTransaction();
		session.update(carona);
		tx.commit();
	}
	
	public boolean cadastrarUsuario(Usuario usuario, Carona carona){
		List<Usuario> passageiros = carona.getPassageiros();
		passageiros.add(usuario);
		carona.setPassageiros(passageiros);
		
		Transaction tx = session.beginTransaction();
		session.update(carona);
		tx.commit();
		
		return true;
	}

	public void recarrega(Carona carona) {
		session.refresh(carona);
	}
	
	
}
